package bTree.LeetCode;

import java.util.List;

public class 反转链表2 {
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
        public ListNode reverseBetween(ListNode head, int left, int right) {
            if(left==right){
                return head;
            }
            ListNode dummy=new ListNode(0,head);
            ListNode p=dummy;
            ListNode preNode=null,leftNode=null,rightNode=null,proNode=null;
            int cnt=0;
            while (p!=null){
                if(cnt==left-1){
                    preNode=p;
                    leftNode=p.next;
                }
                if(cnt==right){
                    rightNode=p;
                    proNode=p.next;
                    break;
                }
                cnt++;
            }
            nodeReverse(leftNode,rightNode);
            preNode.next=rightNode;
            leftNode.next=proNode;
            return dummy.next;
        }

    private void nodeReverse(ListNode leftNode, ListNode rightNode) {
        ListNode left=leftNode,right=leftNode.next;
        while (true){
            ListNode pro=right.next;
            right.next=left;
            left=right;
            right=pro;
            if(left==rightNode){
                break;
            }
        }
    }
}
